import os
import logging
import unittest
import app

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s -%(name)s -%(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def wrap(baseFunc):
    def test_wrap_base(func):
        def test_wrap(self):
            baseFunc(self)
            func(self)

        return test_wrap

    return test_wrap_base


class TestApp(unittest.TestCase):

    def setUp(self):
        app.initdb()

    def tearDown(self):
        app.dropdb()
        db_path = os.path.join(os.path.abspath(os.path.curdir), 'test.db')
        if os.path.exists(db_path):
            os.remove(db_path)

        app.session.close()

    def testinitdb(self):
        """测试创建数据库是否成功"""
        db_path = os.path.join(os.path.abspath(os.path.curdir), 'test.db')
        if os.path.exists(db_path):
            self.assertTrue('db created')
        else:
            self.assertFalse('db create failed')

    def testadduser(self):
        """测试添加一个数据"""
        app.adduser()
        from app import User
        number = app.session.query(User).count()
        app.session.commit()

        self.assertEqual(number, 1)

    @wrap(testadduser)
    def testupdateruser(self):
        """测试更新数据"""
        app.updateusername(1, 'Charles')
        from app import User
        c = app.session.query(User.name).filter_by(_id=1).first()
        app.session.commit()
        self.assertEqual(c[0], 'Charles')

    @wrap(testadduser)
    def testdeleteuser(self):
        """测试删除数据"""
        app.deleteuser(1)
        from app import User
        number = app.session.query(User).filter_by(_id=1).count()
        app.session.commit()
        self.assertEqual(number, 0)

    @wrap(testadduser)
    def testqueryuser(self):
        result = app.queryuser()
        app.session.commit()
        self.assertEqual(len(result), 1)


if __name__ == "__main__":
    unittest.main()
